import 'package:catcher/catcher.dart';

import '../../util/_base_export.dart';
import '../../util/_view_export.dart';
import '../../util/_initwork.dart';

import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:animated_splash_screen/animated_splash_screen.dart';
import 'package:page_transition/page_transition.dart';
import '../../generated/l10n.dart';
import 'package:flutter/services.dart';
import 'package:pushy_flutter/pushy_flutter.dart';
// import 'package:custom_splash/custom_splash.dart';

import '../../blocs/order_detail.dart';
import '../../blocs/product.dart';
import '../../blocs/cart.dart';
import '../../blocs/code.dart';
import '../../blocs/app_lang.dart';
import '../../blocs/menu.dart';
import '../../blocs/helper.dart';
import '../../blocs/profile.dart';
import '../../blocs/sales.dart';

import 'app_frame.dart';

class AppSplashView extends StatefulWidget {
  AppSplashView({Key? key}) : super(key: key);
  _AppSplashViewState createState() => _AppSplashViewState();
}

class _AppSplashViewState extends State<AppSplashView> {
  // void backgroundNotificationListener(Map<String, dynamic> data) {
  //   // Print notification payload data
  //   print('Received notification: $data');

  //   // Notification title
  //   String notificationTitle = 'MyApp';

  //   // Attempt to extract the "message" property from the payload: {"message":"Hello World!"}
  //   String notificationText = data['message'] ?? 'Hello World!';

  //   // Android: Displays a system notification
  //   // iOS: Displays an alert dialog
  //   Pushy.notify(notificationTitle, notificationText, data);

  //   // Clear iOS app badge number
  //   Pushy.clearBadge();
  // }

  // Future<void> initPlatformState() async {
  //   try {
  //     // Start the Pushy service
  //     // Pushy.listen();

  //     print('Pushy listened');
  //     // Set custom notification icon (Android)
  //     Pushy.setNotificationIcon('ic_notify');
  //     // Register the device for push notifications
  //     String deviceToken = await Pushy.register();

  //     // Print token to console/logcat
  //     print('Device token: $deviceToken');

  //     // Send the token to your backend server
  //     // ...

  //     // Update UI with token
  //     // setState(() {
  //     //   _deviceToken = deviceToken;
  //     //   _instruction =
  //     //       Platform.isAndroid ? '(copy from logcat)' : '(copy from console)';
  //     // });
  //   } on PlatformException catch (error) {
  //     // Print to console/logcat
  //     print('Error: ${error.message}');

  //     // Show error
  //     // setState(() {
  //     //   _deviceToken = 'Registration failed';
  //     //   _instruction = '(restart app to try again)';
  //     // });
  //   }

  //   // Listen for push notifications received
  //   Pushy.setNotificationListener(backgroundNotificationListener);

  //   // Listen for push notification clicked
  //   Pushy.setNotificationClickListener((Map<String, dynamic> data) {
  //     // Print notification payload data
  //     print('Notification clicked: $data');

  //     // Extract notification messsage
  //     // String message = data['message'] ?? 'Hello World!';

  //     // Display an alert with the "message" payload value
  //     // showDialog(
  //     //   context: context,
  //     //   builder: (BuildContext context) {
  //     //     return AlertDialog(
  //     //         title: Text('Notification clicked'),
  //     //         content: Text(message),
  //     //         actions: [
  //     //           FlatButton(
  //     //             child: Text('OK'),
  //     //             onPressed: () {
  //     //               Navigator.of(context, rootNavigator: true).pop('dialog');
  //     //             },
  //     //           )
  //     //         ]);
  //     //   },
  //     // );
  //     // Clear iOS app badge number
  //     Pushy.clearBadge();
  //   });
  // }

  @override
  void initState() {
    super.initState();
    Pushy.listen();
    // Pushy.toggleMethodSwizzling(false);
    InitWork.initSync();
    WidgetsBinding.instance?.addPostFrameCallback((_) async {
      // await _initAsync();
    });
  }


  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => ProductBloc()),
        ChangeNotifierProvider(create: (_) => CartBloc()),
        ChangeNotifierProvider(create: (_) => OrderDetailBloc()),
        ChangeNotifierProvider(create: (_) => CodeBloc()),
        ChangeNotifierProvider(create: (_) => MenuBloc()),
        ChangeNotifierProvider(create: (_) => ProfileBloc()),
        ChangeNotifierProvider(create: (_) => SalesBloc()),
        ChangeNotifierProvider(create: (_) => HelperBloc()),
        ChangeNotifierProvider(create: (_) => AppLangBloc()..fetchLocale()),
      ],
      child: Consumer<AppLangBloc>(builder: (context, appmodel, child) {
        return MaterialApp(
          navigatorKey: Catcher.navigatorKey,
          builder: BotToastInit(),
          locale: appmodel.appLocale,
          localizationsDelegates: const [
            S.delegate,
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
          ],
          supportedLocales: S.delegate.supportedLocales,
          theme: ThemeData(
              backgroundColor: Colors.white,
              appBarTheme: AppBarTheme(
                brightness: Brightness.light,
                color: Colors.white,
                // this.elevation,
                // this.shadowColor,
                // this.iconTheme,
                // this.actionsIconTheme,
                // this.textTheme,
                // this.centerTitle,
              ),
              // primarySwatch: Colors.white,
              // textTheme: Theme.of(context).textTheme.apply(
                  // fontFamily: 'NotoSans',
                  // bodyColor: Colors.white,
                  // displayColor: Colors.white,
                  // )
          ),
          home:AnimatedSplashScreen.withScreenFunction(
            // duration: 2500,
            splash: Image.asset(
              'assets/main/launch_logo.png',
            ),
            duration: 3000,
            screenFunction: () async {
              await InitWork.initAsync();
              return AppFrameView();
              // return Text('张三娃');
            },
            // nextScreen: AppFrameView(),
            splashIconSize: 230,
            splashTransition: SplashTransition.fadeTransition,
            // pageTransitionType: PageTransitionType.scale,
            backgroundColor: AppColor.yellowMain,
          ),

          // CustomSplash(
          //   imagePath: 'assets/main/launch_logo.png',
          //   backGroundColor: AppColor.yellowMain,
          //   animationEffect: 'zoom-out', //'fade-in',
          //   // logoSize: 200,
          //   home: AppFrameView(),
          //   // customFunction: duringSplash,
          //   duration: 2500,
          //   type: CustomSplashType.StaticDuration,
          //   // outputAndHome: op,
          // ),
          // navigatorObservers: [
          //   FirebaseAnalyticsObserver(analytics: AppAnalytics.analytics),
          //   BotToastNavigatorObserver(),
          // ],
          navigatorObservers: [
            AppAnalytics.observer,
            BotToastNavigatorObserver(),
          ],
          onGenerateRoute: App.router.generator,
        );
      }),
    );
  }
}

